package com.xcx.minservice.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xcx.minservice.feignclients.AclFeignClient;
import com.xcx.commoncore.request.miniorequest.GetUserFilesRequest;
import com.xcx.commonuntils.returnuntls.ErrorEnum;
import com.xcx.commonuntils.returnuntls.ReturnMessage;
import com.xcx.commonuntils.returnuntls.ReturnMessageUtils;

import com.xcx.commoncore.entity.minioentity.FileSystem;

import com.xcx.minservice.mapper.MinioMapper;
import com.xcx.commoncore.request.miniorequest.GetUserFileTypeRequest;


import com.xcx.minservice.service.MinioService;
import com.xcx.minservice.untilsm.MinioUtil;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Primary
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MinioServiceImpl extends ServiceImpl<MinioMapper, FileSystem> implements MinioService {


    final private MinioUtil minioUtil;
    final private MinioMapper minioMapper;
    final private AclFeignClient aclFeignClient;



    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public ReturnMessage<Object> upload(MultipartFile file,String username,Integer source,Integer type) {

        try {
            FileSystem fileSystem = new FileSystem();

            String fileName = file.getOriginalFilename();
            String extendFileName = fileName.substring(fileName.lastIndexOf('.') + 1);
            String upload = minioUtil.upload(file);
            if ("该文件类型不能上传！".equals(upload)) {
                return ReturnMessageUtils.error(-2, "该文件类型不能上传！");
            }

            fileSystem.setFileName(fileName);
            fileSystem.setFileExt(extendFileName);
            fileSystem.setFilePath(upload);
            fileSystem.setSource(source);
            fileSystem.setUsername(username);
            fileSystem.setType(type);
            if (type == 1){
                aclFeignClient.updateUserFileIndex(username,upload);
            }
            minioMapper.insert(fileSystem);
            return ReturnMessageUtils.success();
        } catch (Exception e) {
            log.error("e:{}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ReturnMessageUtils.errorWithException(e);
        }
    }



//    @Override
//    public ReturnMessage<Object> preview(String fileName) {
//        String preview = minioUtil.preview(fileName);
//
//        return ReturnMessageUtils.success(preview);
//    }

    @Override
    public void download(String fileName, HttpServletResponse res) {
        minioUtil.download(fileName,res);

    }

    @Override
    public ReturnMessage<Object> remove(GetUserFileTypeRequest request) {
        QueryWrapper<FileSystem> fileQueryWrapper = new QueryWrapper<>();
        fileQueryWrapper.eq("username",request.getUsername()).eq("type",request.getType());

        List<FileSystem> fileSystemList = minioMapper.selectList(fileQueryWrapper);
        if (fileSystemList.size() == 0){
            return ReturnMessageUtils.errorWithEum(ErrorEnum.E_USER_FILES_ERRO);

        }
        List<Integer> collectId = fileSystemList.stream().map(FileSystem::getId).collect(Collectors.toList());
        minioMapper.deleteBatchIds(collectId);

        List<String> stringList = fileSystemList.stream().map(FileSystem::getFilePath)
                .collect(Collectors.toList());
        //stringList.stream().forEach(f ->filePathList.add(f.substring(30)));

        for (String s : stringList
             ) {
            String substring = s.substring(30);
            minioUtil.remove(substring);

        }

            return ReturnMessageUtils.success();

    }





    @Override
    public ReturnMessage<List<String>> uploads(MultipartFile[] files,String username) {
        //判断上传文件是否为空
        if (null == files || files.length == 0) {

            return ReturnMessageUtils.errorWithEum(ErrorEnum.E_FILE_UPLOADS_FAIL);
        }
        List<FileSystem> fileSystemList = new ArrayList<>();

        for (MultipartFile file : files
            ) {
                FileSystem fileSystem = new FileSystem();
                String fileName = file.getOriginalFilename();
                String extendFileName = fileName.substring(fileName.lastIndexOf('.') + 1);
                String upload = minioUtil.upload(file);
                if ("该文件类型不能上传！".equals(upload)) {
                    return ReturnMessageUtils.error(-2, "该文件类型不能上传！");
                }

                fileSystem.setFileName(fileName);
                fileSystem.setFileExt(extendFileName);
                fileSystem.setFilePath(upload);
                fileSystem.setSource(1);
                fileSystem.setUsername(username);
                fileSystem.setType(2);
                fileSystemList.add(fileSystem);
        }
        log.info("批量文件对象：",fileSystemList);
        //minioMapper.listInsert(fileSystemList);
        this.saveOrUpdateBatch(fileSystemList);

        return ReturnMessageUtils.success();
    }





//    @Override
//    public ReturnMessage<List<FileSystem>> getUserFiles(GetUserFilesRequest request) {
//        QueryWrapper<FileSystem> fileQueryWrapper = new QueryWrapper<>();
//        fileQueryWrapper.eq("open_id",request.getUsername());
//        List<FileSystem> fileSystems = minioMapper.selectList(fileQueryWrapper);
//        return ReturnMessageUtils.success(fileSystems);
//    }
//
//    @Override
//    public ReturnMessage<List<FileSystem>> getUserFilesByType(GetUserFileTypeRequest request) {
//
//        QueryWrapper<FileSystem> fileQueryWrapper = new QueryWrapper<>();
//        fileQueryWrapper.eq("open_id",request.getUsername()).eq("type",request.getType());
//
//        List<FileSystem> fileSystems = minioMapper.selectList(fileQueryWrapper);
//        if (null == fileSystems) {
//            ReturnMessageUtils.errorWithEum(ErrorEnum.E_FILEUSER_NOTEXIT);
//        }
//        return ReturnMessageUtils.success(fileSystems);
//    }

    /**
     * 根据用户opid返回用户url地址
     * @param request
     * @return
     */
    @Override
    public ReturnMessage<Object> previewByUserName(GetUserFileTypeRequest request) {
        QueryWrapper<FileSystem> fileQueryWrapper = new QueryWrapper<>();
        fileQueryWrapper.select("file_path").eq("username",request.getUsername()).eq("type",request.getType());
        List<FileSystem> fileSystemList = minioMapper.selectList(fileQueryWrapper);
        if (fileSystemList.size() == 0){
            return ReturnMessageUtils.errorWithEum(ErrorEnum.E_USER_FILES_ERRO);
        }
        List<String> collect = fileSystemList.stream().map(FileSystem::getFilePath).collect(Collectors.toList());
        ArrayList<String> filePathList = new ArrayList<>();
        for (String s : collect
        ) {

            String substring = s.substring(30);
            String preview = minioUtil.preview(substring);

            filePathList.add(preview);

        }
        return ReturnMessageUtils.success(filePathList);
    }
}
